package com.ny.zmb.openapi.util;

import com.ny.zmb.openapi.config.OSSConfig;
import com.ny.zmb.openapi.constant.OSSConstant;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OSSUtil {

    @Resource
    private OSSConfig ossConfig;

    /**
     * @param fileName 文件名称
     * @param fileData 文件InputStream
     * @return
     */
    public String uploadFileToOSS(String fileName, InputStream fileData){
        ossConfig.ossClient().putObject(OSSConstant.bucketName,fileName,fileData);
        return "https://" + OSSConstant.bucketName + "." + OSSConstant.endpoint + "/" + fileName;
    }

    /**
     *
     * @param fileName 文件名称
     * @param fileData 文件InputStream
     * @param filePath 上传到指定文件夹中
     * @return
     */
    public String uploadFileToOSS(String fileName, InputStream fileData,String filePath){
        String fileResult = filePath + "/" + fileName;
        ossConfig.ossClient().putObject(OSSConstant.bucketName,fileResult,fileData);
        return "https://" + OSSConstant.bucketName + "." + OSSConstant.endpoint + "/"+ fileResult;
    }

    /**
     *
     * @param fileName 随机文件名称防止重复
     * @param fileData 文件InputStream
     * @return
     */
    public String uploadFileToOSSRandom(String fileName, InputStream fileData){
        String[] split = fileName.split("\\.");
        int size = split.length;
        String fileType = split[size - 1];
        fileName = UUID.randomUUID().toString().replaceAll("-","") + "." + fileType;
        ossConfig.ossClient().putObject(OSSConstant.bucketName,fileName,fileData);
        return "https://" + OSSConstant.bucketName + "." + OSSConstant.endpoint + "/" + fileName;
    }

    /**
     *
     * @param fileName 随机文件名称防止重复
     * @param fileData 文件InputStream
     * @param filePath 上传到指定文件夹中
     * @return
     */
    public String uploadFileToOSSRandom(String fileName, InputStream fileData,String filePath){
        String[] split = fileName.split("\\.");
        int size = split.length;
        String fileType = split[size - 1];
        fileName = UUID.randomUUID().toString().replaceAll("-","") + "." + fileType;
        String fileResult = filePath + "/" + fileName;
        ossConfig.ossClient().putObject(OSSConstant.bucketName,fileResult,fileData);
        return "https://" + OSSConstant.bucketName + "." + OSSConstant.endpoint + "/" + fileResult;
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    public void delFile(String filePath){
        ossConfig.ossClient().deleteObject("",filePath);
    }

    /**
     * 删除文件夹
     * @param filePath
     * @return
     */
    public void delPath(String filePath){
        ossConfig.ossClient().deleteObject("",filePath);
    }
}
